﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UIShare;
using EFong.View.Proxy;
using DevExpress.XtraGrid.Views.Grid;
using EFong.View.Customer;
using System.IO;
using DevExpress.XtraBars;

namespace EFong.View.TouringParty
{
    public partial class Frm_TouringPartyEdit : BasicForm
    {
        private Proxy.BaseServiceProxy _baseProxy { get { return Proxy.BaseServiceProxy.GetInstance(); } }
        private Proxy.MasterServiceProxy _masterProxy { get { return Proxy.MasterServiceProxy.GetInstance(); } }
        private Proxy.BusinessServiceProxy _businessProxy { get { return Proxy.BusinessServiceProxy.GetInstance(); } }

        public Contract.RTouringParty ReturnValue = null;

        public Frm_TouringPartyEdit()
        {
            InitializeComponent();

            gv_TouringPartyItems.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;
        }

        private List<Contract.TourItemType> itemTypeList;

        protected override void InitFields()
        {
            itemTypeList =  _masterProxy.GetTourItemTypeList().ReturnValue;
            this.cmbType.BindingData((from c in itemTypeList
                                      select c.Name).ToList());
        }

        protected override void Events()
        {
            this.btn_CustomerData.Click += (s, e) =>
            {
                editCustomer();
            };
            this.cmb_Customer.EditValueChanged += (s, e) =>
            {
                Contract.RCustomer customer = this.cmb_Customer.GetValue() as Contract.RCustomer;

                if (customer != null)
                {
                    SelCust = _masterProxy.GetCustomerByID(customer.ID).ReturnValue;
                }
                else
                {
                    SelCust = null;
                }
            };
            this.gv_TouringPartyItems.CellValueChanged += (s, e) =>
                {
                    Contract.TouringPartyItem item = this.gv_TouringPartyItems.GetRow(e.RowHandle) as Contract.TouringPartyItem;

                    if (item == null)
                        return;

                    if (e.Column == colQty || e.Column == colPrice || e.Column == colVendorPrice)
                    {
                        gv_TouringPartyItems.SetRowCellValue(e.RowHandle, colTotalVendorPrice, item.Qty * item.VendorPrice);
                    }

                    updateoOrderTotalForGridValueChanged();
                };
            this.gv_TouringPartyItems.CustomDrawCell += (s, e) =>
                {
                    if (e.Column != colUM)
                        return;

                    Contract.TouringPartyItem item = this.gv_TouringPartyItems.GetRow(e.RowHandle) as Contract.TouringPartyItem;

                    if (item == null)
                        return;

                    if(item.Type == string.Empty)
                        item.UM = string.Empty;
                    else
                    {
                        item.UM = (from it in itemTypeList
                                   where it.Name == item.Type
                                   select it.UM).FirstOrDefault();
                    }
                };

            this.spe_AdultQty.ValueChanged += (s, e) => { updateoOrderTotalForGridValueChanged(); };
            this.spe_ChildQty.ValueChanged += (s, e) => { updateoOrderTotalForGridValueChanged(); };
            this.spe_ActAverageAdultPrice.ValueChanged += (s, e) => { updateoOrderTotalForGridValueChanged(); };
            this.spe_ActAverageChildPrice.ValueChanged += (s, e) => { updateoOrderTotalForGridValueChanged(); };

            this.btn_DeleteFile.Click += (s, e) =>
                {
                    txt_DocumentName.SetText(string.Empty);
                    Document = null;
                };
            this.btn_DownloadFile.Click += (s, e) =>
                {
                    if (Document == null)
                        return;

                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.FileName = txt_DocumentName.GetText();
                    saveFileDialog.Filter = "所有文件(*.*)|*.*";
                    DialogResult result = saveFileDialog.ShowDialog();
                    if (result != DialogResult.OK)
                        return;

                    UIOperManager.SaveData(() => { return true; },
                        () =>
                        {
                            writeFile(saveFileDialog.FileName, Document);
                            return true;
                        },
                        "下载成功.");
                };
            this.btn_SelectFile.Click += (s, e) =>
                {
                    OpenFileDialog openFileDialog = new OpenFileDialog();
                    openFileDialog.Filter = "所有文件(*.*)|*.*";
                    DialogResult result = openFileDialog.ShowDialog();
                    if (result != DialogResult.OK)
                        return;

                    UIOperManager.SaveData(() => { return true; },
                        () =>
                        {
                            Document = readFile(openFileDialog.FileName);
                            return true;
                        },
                        string.Empty,
                        () =>
                        {
                            txt_DocumentName.SetText(new FileInfo(openFileDialog.FileName).Name);
                        });
                };

            this.spe_AverageAdultPrice.ValueChanged += (s, e) =>
                {
                    updateOrderTotalForCountAndAveragePrice();
                };
            this.spe_AverageChildPrice.ValueChanged += (s, e) =>
                {
                    updateOrderTotalForCountAndAveragePrice();
                };
        }

        protected override void LoadDatas()
        {
            bds_Customer.BindingData(_masterProxy.GetAllCustomer().ReturnValue);
            this.cmb_OrderUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);

            if (this.cmb_OrderUser.GetValue() == null)
                this.cmb_OrderUser.SetValue(AppParameters.LoginUser);

            this.bds_Vendor.BindingData(_masterProxy.GetAllTourpartyVendor().ReturnValue);
            this.cmb_SalesMan.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);
            this.txt_ProvideTicketUser.Properties.BindingData(_baseProxy.GetEffUser().ReturnValue);

            if (this.cmb_Status.SelectedIndex == -1)
                this.cmb_Status.SelectedIndex = 0;
        }

        private void bar_Main_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "bbt_Save":
                    this.save();
                    break;
                case "bbt_Close":
                    this.Close();
                    break;
                default:
                    break;
            }
        }

        private string returnRef;

        private void save()
        {
            Contract.TouringParty order = null;

            UIOperManager.SaveData(
                () =>
                {
                    return true;
                },
                () =>
                {
                    order = getOrder();
                    updateToOrder(order);
                    var result = _masterProxy.UpdateTouringParty(Order);
                    if (result.IsSuccess)
                    {
                        returnRef = result.ReturnValue;
                        this.txt_OrderRef.Text = returnRef;
                    }

                    return result.IsSuccess;
                },
                string.Empty,
                () =>
                {
                    DialogResult = DialogResult.OK;
                    MsgBox.Info(string.Format("{0} 保存成功", returnRef));
                    this.Close();

                    ReturnValue = new Contract.RTouringParty()
                    {
                        ID = Order.ID,
                        Customer = Order.Customer.Name,
                        OrderDate = Order.OrderDate.Value,
                        Ref = returnRef,
                        Name = Order.Name
                    };
                });
        }

        private void editCustomer()
        {
            if (SelCust == null)
                return;

            Frm_CustomerEdit frm = new Frm_CustomerEdit();
            frm.Text = "客户详细资料";
            if (!AppParameters.AllowEditCustomer)
                frm.ViewState = ViewStates.BROWSER;
            else if (ViewState == ViewStates.BROWSER)
                frm.ViewState = ViewStates.BROWSER;
            frm.Load += (s, e) =>
            {
                frm.CurCust = SelCust;
            };
            FormOpener.ShowDialog(frm);
        }
        
        bool isUpdating = false;
        private void updateOrderTotalForCountAndAveragePrice()
        {
            if (isUpdating)
                return;

            isUpdating = true;

            Contract.TouringParty order = getOrder();

            this.spe_OrderTotalPrice.SetValue(order.TotalPrice);//总应收
            this.txt_OrderTotalVendorPrice.SetText(order.TotalVendorPrice);
            this.txt_OrderTotalProfit.SetText(order.TotalProfit);

            isUpdating = false;
        }

        private void updateoOrderTotalForGridValueChanged()
        {
            
            if (isUpdating)
                return; 

            isUpdating = true;

            this.gv_TouringPartyItems.PostEditor();
            Contract.TouringParty order = getOrder();

            //order.AverageAdultPrice = order.CalcAverageAdultPrice();
            //order.AverageChildPrice = order.CalcAverageChildPrice();

            this.spe_AverageAdultPrice.SetValue(order.AverageAdultPrice);//成人应收
            this.spe_AverageChildPrice.SetValue(order.AverageChildPrice);//儿童应收
            this.spe_AverageAdultVendorPrice.SetValue(order.AverageAdultVendorPrice);//成人应付
            this.spe_AverageChildVendorPrice.SetValue(order.AverageChildVendorPrice);//儿童应付
            this.spe_OrderTotalPrice.SetValue(order.TotalPrice);//总应收
            this.txt_OrderTotalVendorPrice.SetText(order.TotalVendorPrice);
            this.txt_OrderTotalProfit.SetText(order.TotalProfit);

            isUpdating = false;
        }

        #region Order
        // TouringParty
        private Contract.TouringParty _order;
        public Contract.TouringParty Order
        {
            get { return _order; }
            set
            {
                _order = value;
                onOrderChanged();
            }
        }

        private void onOrderChanged()
        {
            if (Order == null)
            {
            }
            else
            {
                if (Order.OrderUser != null)
                    this.cmb_OrderUser.SetValue(Order.OrderUser);
                if (Order.OrderDate != null)
                    this.dte_OrderDate.SetValue(Order.OrderDate);
                this.txt_OrderRef.SetText(Order.Ref);
                if (Order.Ref == string.Empty)
                    this.txt_OrderRef.SetText("(保存时自动获取)");
                this.cmb_Customer.SetValue(Order.Customer);
                SelCust = Order.Customer;

                this.bds_TouringPartyItem.BindingData(Order.Items);

                this.txt_OrderRemark.SetText(Order.Remark);

                spe_ChildQty.SetValue(Order.ChildQty);
                spe_AdultQty.SetValue(Order.AdultQty);
                //cmb_ChildType.SetValue(Order.ChildType);

                this.cmb_SalesMan.SetValue(Order.SalesMan);
                this.txt_ProvideTicketUser.SetValue(Order.ProvideTicketUser);

                txt_DocumentName.SetText(Order.DocumentName);
                Document = Order.Document;

                txt_Name.SetText(Order.Name);

                txt_CPerson.SetText(Order.ContactPerson);
                txt_CPersonTel.SetText(Order.ContactPersonTel);


                this.txt_OrderTotalVendorPrice.SetText(Order.TotalVendorPrice);
                this.txt_OrderTotalProfit.SetText(Order.TotalProfit);

                this.spe_AverageAdultPrice.SetValue(Order.AverageAdultPrice);//成人应收
                this.spe_ActAverageAdultPrice.SetValue(Order.ActAverageAdultPrice);//成人应收
                this.spe_AverageChildPrice.SetValue(Order.AverageChildPrice);//儿童应收
                this.spe_ActAverageChildPrice.SetValue(Order.ActAverageChildPrice);//儿童应收

                this.chk_ShowOnWeb.SetValue(Order.IsShowOnWeb);

                if (!string.IsNullOrEmpty(Order.Status))
                    this.cmb_Status.SetValue(Order.Status);
            }
        }

        private Contract.TouringParty getOrder()
        {
            Contract.TouringParty order = new Contract.TouringParty();

            order.Name = this.txt_Name.GetText();

            order.ContactPerson = txt_CPerson.GetText();
            order.ContactPersonTel = txt_CPersonTel.GetText();

            order.OrderUser = this.cmb_OrderUser.GetValue() as Contract.User;
            order.OrderDate = this.dte_OrderDate.GetValue(AppParameters.FetureDateTime);
            order.Customer = SelCust;

            order.SalesMan = this.cmb_SalesMan.GetValue() as Contract.User;
            order.ProvideTicketUser = this.txt_ProvideTicketUser.GetValue() as Contract.User;

            order.Remark = this.txt_OrderRemark.GetText();

            order.ChildQty = (int)spe_ChildQty.GetValue();
            order.AdultQty = (int)spe_AdultQty.GetValue();

            order.DocumentName = txt_DocumentName.GetText();
            order.Document = Document;

            order.Items = this.bds_TouringPartyItem.DataSource as List<Contract.TouringPartyItem>;
            if (order.Items == null)
                order.Items = new List<Contract.TouringPartyItem>();

            order.ActAverageAdultPrice = spe_ActAverageAdultPrice.GetValue();
            order.ActAverageChildPrice = spe_ActAverageChildPrice.GetValue();

            order.Status = this.cmb_Status.GetValue() as String;
            order.IsShowOnWeb = this.chk_ShowOnWeb.GetValue();

            return order;
        }

        private void updateToOrder(Contract.TouringParty order)
        {
            Order.Name = order.Name;
            Order.Customer = order.Customer;

            Order.ContactPerson = order.ContactPerson;
            Order.ContactPersonTel = order.ContactPersonTel;

            Order.OrderDate = order.OrderDate;

            Order.OrderUser = order.OrderUser;

            Order.SalesMan = order.SalesMan;
            Order.ProvideTicketUser = order.ProvideTicketUser;

            Order.Remark = order.Remark;

            Order.ChildQty = order.ChildQty;
            Order.AdultQty = order.AdultQty;
            //Order.ChildType = order.ChildType;
            Order.DocumentName = order.DocumentName;
            Order.Document = order.Document;

            Order.ActAverageAdultPrice = order.ActAverageAdultPrice;
            Order.ActAverageChildPrice = order.ActAverageChildPrice;

            Order.Status = order.Status;
            Order.IsShowOnWeb = order.IsShowOnWeb;
        }
        #endregion


        #region Customer
        private Contract.Customer _selCust;
        public Contract.Customer SelCust
        {
            get { return _selCust; }
            set
            {
                _selCust = value;
                onSelCustChanged();
            }
        }

        private void onSelCustChanged()
        {
            if (SelCust == null)
            {
                this.cmb_SalesMan.SetValue(default(Contract.User));
            }
            else
            {
                this.cmb_SalesMan.SetValue(SelCust.Salesman);
            }
        }
        #endregion

        #region Document
        public byte[] Document { get; set; }
        #endregion


        private byte[] readFile(string fileName)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Read))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    int count;

                    while ((count = fileStream.ReadByte()) != -1)
                    {
                        memoryStream.WriteByte((byte)count);
                    }

                    return memoryStream.ToArray();
                }
            }
        }

        private void writeFile(string fileName, byte[] file)
        {
            using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
            {
                fileStream.Write(file, 0, file.Length);
                fileStream.Flush();
            }
        }


        protected override void OnViewStateChanged()
        {
            switch (ViewState)
            {
                case ViewStates.BROWSER:
                    //bbt_Save.Visibility = BarItemVisibility.Never;
                    //spe_AdultQty.ReadOnly(true);
                    //spe_AverageAdultPrice.ReadOnly(true);
                    //spe_ChildQty.ReadOnly(true);
                    //txt_CPerson.ReadOnly(true);
                    //txt_CPersonTel.ReadOnly(true);
                    //txt_Name.ReadOnly(true);
                    //txt_OrderRemark.ReadOnly(true);
                    //cmb_ChildType.ReadOnly(true);
                    //cmb_Customer.ReadOnly(true);
                    //btn_DeleteFile.Visible = false;
                    //btn_SelectFile.Visible = false;
                    break;
                default:
                    break;
            }
        }
    }
}
